Program main
use type
use var
use parallel
implicit none
include 'mpif.h'
integer ::  step,cur_sycle, iout, trj_sycle, trj_step, trj_y 
real(dp) :: last_E(5) 
real (dp) :: clock_start,clock_finish,c_ini,c_fin
logical :: trjexist
character (len=8) :: fname='Energy', fname2='Q'
Character(len=10) :: namefile1, dir_name

CALL MPI_INIT(IERR)
CALL MPI_COMM_SIZE(MPI_COMM_WORLD, SIZE, IERR)
CALL MPI_COMM_RANK(MPI_COMM_WORLD, ID, IERR)

if (ID == master) then
   call cpu_time(clock_start)
   open(222,file='data.out')
   open(999,file='x.xyz')
   open(900,file='lastE')
endif 

call input()
iout = 200 + ID + 1
write(namefile1,'(I10)')int(ID+1)
if (restart == 0) then
   frame = 0
   if (traj(2) == 1) then
      OPEN ( iout , FILE = trim(adjustr(fname2))//trim(adjustl(namefile1)),form='UNFORMATTED', access='SEQUENTIAL')
   else
      if (ID == 0) OPEN ( iout , FILE = trim(adjustr(fname2))//trim(adjustl(namefile1)),form='UNFORMATTED', access='SEQUENTIAL')
   endif
else
   if (traj(2) == 1) then
      OPEN ( iout , FILE = trim(adjustr(fname2))//trim(adjustl(namefile1)),form='UNFORMATTED', access='SEQUENTIAL',status='old')
   else
      if (ID == 0) OPEN ( iout , FILE = trim(adjustr(fname2))//trim(adjustl(namefile1)),form='UNFORMATTED', access='SEQUENTIAL',status='old')
   endif
endif

write(namefile1,'(I10)')int(ID+1)
iout = 300 + ID + 1 
open(iout,FILE=trim(adjustr(fname))//trim(adjustl(namefile1)),STATUS='replace')
write(iout,*)"@ step LdG Elastic Energy"

call initial(0)
if (restart == 1) then
   call rtraj(trj_sycle, trj_step, trj_y)
   if (traj(2) == 0) then
      step =0
      cur_sycle = trj_sycle + 1
      call movenp(-1,0)
   else
      cur_sycle = trj_sycle 
      step = trj_step
      trj_E = 0.d0
   endif
endif

if (number_NP > 0) then
   if (restart == 0) call position_NP()
   call make_np()
endif
call define_parameter()

if (restart == 0) then
   cur_sycle = 1
   step = 0
   trj_y = 0
endif
CALL MPI_BARRIER(MPI_COMM_WORLD, IERR)

DO while (cur_sycle<=sycle)

!call qmga(cur_sycle,0)
if (method==1.or.method==3) then
   call mc(cur_sycle,step,trj_y,last_E)
   write(*,*) " last energy of MC sycle ", last_E
endif

if (method==3) write(*,*) "At step ", step ," method change from MC to GL" 

!Gibzburg - Landau
if (method==2.or.method==3) then
   CALL GL(cur_sycle,step,trj_y,last_E)
   CALL MPI_BARRIER(MPI_COMM_WORLD, IERR)
   if (ID == master) write(*,*) " last energy of GL cycle ", cur_sycle
   CALL MPI_BARRIER(MPI_COMM_WORLD, IERR)
   write(*,'(I7,X,5(f15.6))')ID+1,last_E
endif

CALL MPI_BARRIER(MPI_COMM_WORLD, IERR)
if (number_NP>0.and.1<sycle) call movenp(cur_sycle,last_E) 


cur_sycle = cur_sycle + 1
step = 0
trj_y = 0
enddo

if (traj(2)==1) call wtraj(cur_sycle-1,step,trj_y)

!call qmga(1,0)
CALL MPI_BARRIER(MPI_COMM_WORLD, IERR)

if (ID == master) then
   call cpu_time (clock_finish)
   call timer(clock_finish,clock_start)
endif

CALL MPI_FINALIZE(IERR)
end program main
